<?php

namespace app\model;

use support\Model;

/**
 * 积分日志表
 *
 * 字段说明（参考 @20250802061259_create_score_log_table_migration.php 和 @20250803064743_add_columns_to_score_log_migration.php）:
 * - id         : 主键，自增
 * - user_id    : 用户ID
 * - score      : 积分变动数量
 * - type       : 类型（如充值、消费等）
 * - dir        : 方向（1-收入，2-支出）
 * - action     : 操作
 * - comment    : 备注
 * - item_id    : 相关ID
 * - created_at : 创建时间（时间戳）
 * - updated_at : 更新时间（时间戳）
 */

class ScoreLogModel extends Model
{
    /**
     * The table associated with the model.
     *
     * @var string
     */
    protected $table = 'score_log';

    /**
     * The primary key associated with the table.
     *
     * @var string
     */
    protected $primaryKey = 'id';

    /**
     * Indicates if the model should be timestamped.
     *
     * @var bool
     */
    public $timestamps = false;

    /**
     * 可批量赋值字段
     * @var array
     */
    protected $fillable = [
    ];

    const IN = 1;
    const OUT = 2;

    /**
     * 添加一条记录
     * @param mixed $user_id
     * @param mixed $score
     * @param mixed $type
     * @param mixed $dir
     * @param mixed $action
     * @param mixed $extra
     * @return void
     */
    static public function add($user_id,$score,$type,$dir,$action,$extra = []){
        $log = new self();
        $log->user_id = $user_id;
        $log->score = $score;
        $log->type = $type;
        $log->dir = $dir;
        $log->created_at = time();
        $log->updated_at = time();
        $log->action = $action;

        if(!empty($extra['item_id'])){
            $log->item_id = $extra['item_id'];
        }
        
        if(!empty($extra['card_user_id'])){
            $log->card_user_id = $extra['card_user_id'];
        }

        if(!empty($extra['comment'])){
            $log->comment = $extra['comment'];
        }

        $log->save();
    }

    static public function getActionText($action){
        $acs = config('score.action');

        return $acs[$action] ?? $action;
    }
}